package com.aaa.gateway.filter;

import com.aaa.utils.TokenUtils;
import com.aaa.vo.Result;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取请求路径
        String path = request.getPath().toString();

        //判断是否为请求路径
        if("/login".equals(path)){
            return chain.filter(exchange);
        }
        //获取token 验证
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isNotBlank(token)&& TokenUtils.validateToken(token)&&redisTemplate.hasKey(token)){
            //刷新token的过期时间
            redisTemplate.expire(token,30, TimeUnit.MINUTES);
            return chain.filter(exchange);
        }
        //如果没有登陆
        Result<String> result = new Result<>(401,"登录失效");
        //做JSON转换
        byte[] bytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        //调用bufferFactory方法生成DataBuffer对象
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        //调用Mono中的just方法返回要写给前端的JSON数据
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
